import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { SongMV } from './entities/song.entity';
import { MvScene } from '../mv-scene/entities/mv-scene.entity';
import { CreateSongDto } from './dto/create-song.dto';
import { UpdateSongDto } from './dto/update-song.dto';

@Injectable()
export class SongService {
  constructor(
    @InjectRepository(SongMV)
    private readonly songRepository: Repository<SongMV>,
    @InjectRepository(MvScene)
    private readonly sceneRepository: Repository<MvScene>,
  ) {}

  // 创建歌曲
  async create(createSongDto: CreateSongDto): Promise<SongMV> {
    const { scenes, ...songData } = createSongDto;

    // 创建歌曲
    const song = this.songRepository.create(songData);

    // 如果有场景数据，创建场景并关联
    if (scenes && scenes.length > 0) {
      const sceneEntities = scenes.map(scene => this.sceneRepository.create(scene));
      song.scenes = await this.sceneRepository.save(sceneEntities);
    }

    return this.songRepository.save(song);
  }

  // 查询所有歌曲
  async findAll(): Promise<SongMV[]> {
    return this.songRepository.find({ relations: ['scenes'] });
  }

  // 查询单个歌曲
  async findOne(id: number): Promise<SongMV> {
    const song = await this.songRepository.findOne({
      where: { id },
      relations: ['scenes'],
    });

    if (!song) {
      throw new NotFoundException(`Song with ID ${id} not found`);
    }

    return song;
  }

  // 更新歌曲
  async update(id: number, updateSongDto: UpdateSongDto): Promise<SongMV> {
    const song = await this.findOne(id);

    // 更新歌曲数据
    Object.assign(song, updateSongDto);

    // 如果有场景数据，更新场景
    if (updateSongDto.scenes && updateSongDto.scenes.length > 0) {
      const sceneEntities = updateSongDto.scenes.map(scene => this.sceneRepository.create(scene));
      song.scenes = await this.sceneRepository.save(sceneEntities);
    }

    return this.songRepository.save(song);
  }

  // 删除歌曲
  async remove(id: number): Promise<void> {
    const song = await this.findOne(id);
    await this.songRepository.remove(song);
  }
}